package cn.topevery.garden.wapi.controller;

import cn.topevery.garden.dal.logic.ProjectFileLogic;
import cn.topevery.garden.dal.logic.ProjectInfoLogic;
import cn.topevery.garden.dal.logic.ProjectProgressLogic;
import cn.topevery.garden.entity.impot.ProjectInfoImportParam;
import cn.topevery.garden.entity.po.ProjectFile;
import cn.topevery.garden.entity.po.ProjectInfo;
import cn.topevery.garden.entity.po.ProjectProgress;
import cn.topevery.garden.entity.query.ProjectInfoQuery;
import cn.topevery.garden.entity.vo.ProjectInfoVO;
import cn.topevery.garden.wapi.utils.ExcelUtils;
import com.github.dozermapper.core.Mapper;
import hw.topevery.basis.entity.po.SysUser;
import hw.topevery.framework.db.entity.DataPager;
import hw.topevery.framework.util.ExcelUtil;
import hw.topevery.framework.web.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 工程管理
 *
 * @author code -generate
 * @created 2021 -09-01 17:45:43
 * @date 2021 -09-01
 */
@Api(tags = "工程管理接口")
@RestController
@RequestMapping("/projectInfo")
public class ProjectInfoController extends BaseController {

    /**
     * The Mapper.
     */
    @Autowired
    private Mapper mapper;

    /**
     * The Project info logic.
     */
    @Autowired
    ProjectInfoLogic projectInfoLogic;

    /**
     * The Project file logic.
     */
    @Autowired
    ProjectFileLogic projectFileLogic;

    /**
     * The Project progress logic.
     */
    @Autowired
    ProjectProgressLogic projectProgressLogic;


    /**
     * 获取分页列表
     *
     * @param query the query
     * @return json result
     * @author wenzhao.lin
     * @created 2021 -09-01 17:45:43 List page json result.
     */
    @ApiOperation(value = "获取页列表")
    @PostMapping("/listPage")
    public JsonResult<DataPager<ProjectInfo>> listPage(@RequestBody ProjectInfoQuery query) {
        return JsonResult.ok(projectInfoLogic.listPage(query));
    }

    /**
     * 描述 项目信息保存.
     *
     * @param dto the dto
     * @return the json result
     * @author wenzhao.lin
     * @created 2021 -09-01 17:45:43 Save or update json result.
     */
    @ApiOperation("新增/编辑项目信息")
    @PostMapping("/saveOrUpdate")
    public JsonResult<Boolean> saveOrUpdate(@Valid @RequestBody ProjectInfo dto) {
        boolean isSave = projectInfoLogic.saveOrUpdate(getUser().userId,dto);
        if(isSave){
            // 保存附件
            projectFileLogic.saveOrUpdate(getUser().userId, dto.getId(), dto.getFileList(),1);
        }
        return JsonResult.ok(true);
    }

    /**
     * 描述 项目流程信息保存
     *
     * @param dto the dto
     * @return the json result
     * @author wenzhao.lin
     * @created 2021 -09-01 17:45:43 Save or update progress json result.
     */
    @ApiOperation("新增/编辑 项目流程信息")
    @PostMapping("/saveOrUpdateProgress")
    public JsonResult<Boolean> saveOrUpdateProgress(@Valid @RequestBody ProjectProgress dto) {
        boolean isSave = projectProgressLogic.saveOrUpdate(getUser().userId,dto);
        if(isSave){
            // 保存附件
            projectFileLogic.saveOrUpdate(getUser().userId, dto.getId(), dto.getFileList(),2);

            // 更新项目状态
            ProjectInfo projectInfo = projectInfoLogic.getEntity(dto.getProjectId());
            projectInfo.setActName(dto.getName());
            //projectInfo.setCompany(dto.getMainDept());
            //projectInfo.setCompanyUser(dto.getMainUser());
            projectInfoLogic.saveOrUpdate(getUser().userId, projectInfo);
        }
        return JsonResult.ok(true);
    }

    /**
     * 描述 获取详情
     *
     * @param id the id
     * @return the info by id
     * @author wenzhao.lin
     * @created 2021 -09-01 17:45:43
     */
    @ApiOperation("获取详情")
    @GetMapping("/getInfoById")
    public JsonResult getInfoById(@RequestParam Integer id) {
        ProjectInfo projectInfo = projectInfoLogic.getEntity(id);

        // 获取附件 type:1-项目，2-流程
        List<ProjectFile> list = projectFileLogic.getListByPid(id, 1);
        projectInfo.setFileList(list);

        // 获取流程
        List<ProjectProgress> progressList = projectProgressLogic.getListByPid(id);
        for(ProjectProgress projectProgress : progressList){
            List<ProjectFile> tempList = projectFileLogic.getListByPid(projectProgress.getId(), 2);
            projectProgress.setFileList(tempList);
        }
        projectInfo.setProjectProgressList(progressList);

        return JsonResult.ok(projectInfo);
    }

    /**
     * 描述 获取流程详情
     *
     * @param id the id
     * @return the info by id
     * @author wenzhao.lin
     * @created 2021 -09-01 17:45:43
     */
    @ApiOperation("获取流程详情")
    @GetMapping("/getProgressInfoById")
    public JsonResult getProgressInfoById(@RequestParam Integer id) {
        ProjectProgress projectProgress = projectProgressLogic.getEntity(id);

        // 获取附件 type:1-项目，2-流程
        List<ProjectFile> list = projectFileLogic.getListByPid(id, 2);
        projectProgress.setFileList(list);

        return JsonResult.ok(projectProgress);
    }

    /**
     * 描述 根据自增ID批量删除.
     *
     * @param ids the ids
     * @return the json result
     * @author wenzhao.lin
     * @created 2021 -09-01 17:45:43 Delete batch by id json result.
     */
    @ApiOperation("根据自增ID批量删除")
    @GetMapping("/deleteBatchById")
    public JsonResult<Boolean> deleteBatchById(@RequestParam Integer[] ids) {
        projectInfoLogic.deleteBatchById(getUser().userId,ids);
        return JsonResult.ok(true);
    }

    /**
     * 描述 导出信息.
     *
     * @param query    the query
     * @param response the response
     * @author wenzhao.lin
     * @created 2021 -09-01 17:45:43 Export.
     */
    @ApiOperation("导出信息")
    @GetMapping("/export")
    public void export(ProjectInfoQuery query, HttpServletResponse response) {
        List<ProjectInfo> list = projectInfoLogic.listPage(query).records;
        ExcelUtil.exportExcel(list, "", "sheet1", ProjectInfo.class, "", response);
    }

    /**
     * 描述 检查导入数据.
     *
     * @param file the file
     * @return the json result
     * @author wenzhao.lin
     * @created 2021 -08-19 09:35:59 Analysis excel data json result.
     */
    @PostMapping("/analysisExcel")
    public JsonResult AnalysisExcelData(@RequestParam("file") MultipartFile file) {
        boolean isPass = true;
        String msg = "";
        List<ProjectInfoVO> persons = null;
        try {
            persons = ExcelUtils.importExcel(file, 0, 1, ProjectInfoVO.class);
        } catch (Exception e) {
            msg = "解析发生错误，请按照模板格式填写数据！";
            return JsonResult.error(msg);
        }

        List<ProjectInfoVO> newData = new ArrayList<>();
        for (ProjectInfoVO p : persons) {
            String anaylsisRes = "";
            if (p.getSid() == 0 && p.getName() == null) {
                break;
            }
            boolean isExists1 = projectInfoLogic.isExit("c_title", p.getTitle());
            if (isExists1) {
                anaylsisRes += "文号与现有重复；";
            }

            if (anaylsisRes.length() > 0) {
                p.setPass(false);
                p.setAnalysisRes(anaylsisRes);
            } else {
                p.setPass(true);
                p.setAnalysisRes("验证通过");
            }
            newData.add(p);
        }
        isPass = !newData.stream().anyMatch(a -> a.isPass() == false);
        Map<String, Object> res = new HashMap<>();
        res.put("isPass", isPass);
        res.put("data", newData);
        return JsonResult.ok(res);
    }

    /**
     * 描述 导入数据.
     *
     * @param param the param
     * @return the json result
     * @author wenzhao.lin
     * @created 2021 -08-19 09:35:53 Import excel data json result.
     */
    @PostMapping("/importExcel")
    public JsonResult importExcelData(@RequestBody ProjectInfoImportParam param) {

        SysUser user = getUser();
        if (param.getTableData() != null && param.getTableData().size() > 0) {

            for (ProjectInfoVO p : param.getTableData()) {
                ProjectInfo tmp = new ProjectInfo();

                tmp.setCode(p.getCode());
                tmp.setName(p.getName());
                tmp.setShortName(p.getShortName());
                tmp.setTitle(p.getTitle());
                tmp.setMgrDept(p.getMgrDept());
                tmp.setBeginDate(p.getBeginDate());
                tmp.setActName(p.getActName());
                tmp.setMgrUser(p.getMgrUser());
                tmp.setMgrUserPhone(p.getMgrUserPhone());
                tmp.setMoneySrc(p.getMoneySrc());
                tmp.setPayProgress(p.getPayProgress());
                tmp.setBuildNature(p.getBuildNature());
                tmp.setPlanMoney(p.getPlanMoney());
                tmp.setEstimateMoney(p.getEstimateMoney());
                tmp.setAuditMoney(p.getAuditMoney());
                tmp.setContent(p.getContent());
                tmp.setEndDate(p.getEndDate());
                tmp.setRemark(p.getRemark());
                tmp.setProgressContent(p.getProgressContent());
                tmp.setCompany(p.getCompany());
                tmp.setCompanyUser(p.getCompanyUser());
                tmp.setCompanyUserPhone(p.getCompanyUserPhone());

                projectInfoLogic.saveOrUpdate(user.id.toString(),tmp);
            }
        } else {
            return JsonResult.error("导入数据列表不能为空");
        }
        return JsonResult.ok();
    }
}
